package top.songxs.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import top.songxs.base.BaseController;
import top.songxs.entity.HouseImage;
import top.songxs.result.Result;
import top.songxs.service.HouseBrokerService;
import top.songxs.service.HouseImageService;
import top.songxs.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {
    @Reference
    private HouseImageService houseImageService;
    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Model model){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        return "houseImage/upload";
    }
    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId, @PathVariable Integer type, @RequestParam(value = "file") MultipartFile [] files) throws IOException {
        if(files!=null){
            for(MultipartFile file:files){
                //上传图片到七牛云  lvy.ou2.jpg
                String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString();//没有扩展名  32141234aerqreqadfadf2342134
                fileName+=extName; //32141234aerqreqadfadf2342134.jpg
                QiniuUtil.upload2Qiniu(file.getBytes(),fileName);
                //QiniuUtil.upload2Qiniu(file.getBytes(),file.getOriginalFilename()); //可能导致同名文件覆盖
                //写图片信息到数据库
                HouseImage houseImage = new HouseImage();
                houseImage.setType(type);
                houseImage.setHouseId(houseId);
                houseImage.setImageUrl("http://qny.songxs.top/"+fileName);//七牛云外链地址 为了页面展示图片
                houseImage.setImageName(fileName); //为了删除七牛云上的图片 这个字段也可以写原始文件名file.getOriginalFilename()，下载方便
                houseImageService.insert(houseImage);
            }
        }

        return Result.ok();
    }
    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId,@PathVariable Long id){
        HouseImage houseImage = houseImageService.getById(id);
        //删除七牛云上的图片
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName()); //不能使用外链地址，要使用图片名称
        //删除数据库中的图片
        houseImageService.delete(id);
        return "redirect:/house/"+houseId;
    }
}
